const express = require('express')
const mongoose = require('mongoose')
const app = express()
const JwtUtil = require('./plugins/jwt')
var cors = require("cors");
app.use(express.json())
app.use(express.static("./public"))
app.use(cors());
// mongodb数据库连接及端口配置
const port = process.env.PORT || 8002
app.listen(port, () => {
    console.log(`server running on ${port}`)
})
mongoose.connect('mongodb://localhost:27017/jdmpresystem', { useNewUrlParser: true, useUnifiedTopology: true })
    .then(() => console.log('Mongodb Connected'))
    .catch(err => console.log(err))

//失败

// //CORS设置跨域访问
// app.all('*', (req, res, next) => {
//     res.header("Access-Control-Allow-Credentials", true)
//     res.header("Access-Control-Allow-Origin", "*");
//     res.header("Access-Control-Allow-Headers", "Authorization, X-Requested-With");
//     res.header("Access-Control-Allow-Methods", "*");
//     res.header("Content-Type", "application/json; charset=utf-8")
//     next();
// });
//失败
// app.use((req, res, next) => {
//     //判断路径
//     if (req.path !== '/' && !req.path.includes('.')) {
//         res.set({
//             'Access-Control-Allow-Credentials': true, //允许后端发送cookie
//             'Access-Control-Allow-Origin': '*', //任意域名都可以访问,或者基于我请求头里面的域
//             'Access-Control-Allow-Headers': 'X-Requested-With,Authrization', //设置请求头格式和类型
//             'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',//允许支持的请求方式
//             'Content-Type': 'application/json; charset=utf-8'//默认与允许的文本格式json和编码格式
//         })
//     }
//     req.method === 'OPTIONS' ? res.status(204).end() : next()
// })

app.use((req, res, next) => {
    // 获取当前访问的api地址
    const url = req._parsedUrl.pathname
    // 不需要进行验证的api，白名单
    var urlArr = ['/api/user/login', '/api/user/register', '/api/user/Isun', '/api/user/publicKey',
        '/api/user/IdentifyForgetPhone', '/api/user/changePass', '/api/user/IdentifySmscode']
    console.log(url);
    if (urlArr.indexOf(url) >= 0) {
        next()
        return false
    } else {
        const token = req.headers['authorization']
        let jwt = new JwtUtil(token)
        let result = jwt.verifyToken()
        if (result == 'err') {
            res.status(403).send({ status: 403, msg: '登录已过期,请重新登录', res: result });
        } else {
            next();
        }
    }
})


// 创建api
// 引入users.js并使用接口
// app.use((req, res, next) => {
//     console.log(new Date(), req.headers['authorization']);
//     next();
// })
const users = require('./routes/user')
app.use('/api/user', users)

const phone = require('./routes/phone');
app.use('/api/phone', phone)

const cart = require('./routes/shopcart')
app.use('/api/cart', cart)

const order = require('./routes/order')
app.use('/api/order', order)